#include "N1Trace.h"
#include "N1Lib.h"

#ifdef N1TRACE

const uint32 gMaxTraceLogLevel = 124;

class N1TraceLog : public N1Object
{
public:
    N1NAME_DECL

    N1TraceLog(uint32 maxLevel);
    virtual ~N1TraceLog();

    void addTrace(pcstr str);
    void removeLastTrace();

    void startTrace() { m_traceStarted = true; };
    void stopTrace() { m_traceStarted = false; };

    //getCurrentTraceLevel
    //getTraceStringByLevel

private:
    typedef struct 
    {
        pcstr m_traceString;
    } 
    N1TraceRecord;

    uint32        m_traceLevel;
    uint32        m_maxTraceLevel;
    N1TraceRecord m_traceLog;
    bool          m_traceStarted;
};

N1NAME_DEF(N1TraceLog)

N1TraceLog::N1TraceLog(uint32 maxLevel) : m_traceLevel(0), m_maxTraceLevel(maxLevel), m_traceStarted(false)
{
    m_traceLog = N1Malloc(maxLevel * sizeof(N1TraceRecord));
}

N1TraceLog::~N1TraceLog()
{
    N1Free(m_traceLog);
}

void N1TraceLog::addTrace(pcstr str)
{
    if(m_traceStarted)
    {
        m_traceLog[m_traceLevel].m_traceString = str;
        m_traceLevel++;
    }
}

void N1TraceLog::removeLastTrace()
{
    m_traceLevel--;
}


static N1String gN1TraceLog("N1TraceLogDictionaryKey");


N1TraceClass::N1TraceClass(pcstr traceString)
{
    N1Dictionary* dict = N1Thread::currentThread()->getThreadDictionary();
    m_traceLog = (N1TraceLog*)dict->objectForKey(gN1TraceLog);

    if(m_traceLog==NULL)
    {  
        m_traceLog = new N1TraceLog(gMaxTraceLogLevel);
        dict->setObject(gN1TraceLog, m_traceLog);
        m_traceLog->release();
    }
    m_traceLog->addTrace(traceString);
}

N1TraceClass::~N1TraceClass()
{
    m_traceLog->removeLastTrace();
}

void N1TraceClass::startTrace()
{
    N1Dictionary* dict = N1Thread::currentThread()->getThreadDictionary();
    N1TraceLog* traceLog = (N1TraceLog*)dict->objectForKey(gN1TraceLog);
    traceLog->startTrace();
}

void N1TraceClass::stopTrace()
{
    N1Dictionary* dict = N1Thread::currentThread()->getThreadDictionary();
    N1TraceLog* traceLog = (N1TraceLog*)dict->objectForKey(gN1TraceLog);
    traceLog->stopTrace();
}
 
void N1TraceClass::setMaxTraceLevel(uint32 max)
{
}

uint32 N1TraceClass::getMaxTraceLevel()
{
    retunr 0;
}

#endif
